"use client";

import * as React from "react";

import { type Point, type TElement } from "platejs";

import {
  type ComboboxItemProps,
  Combobox,
  ComboboxGroup,
  ComboboxGroupLabel,
  ComboboxItem,
  ComboboxPopover,
  ComboboxProvider,
  ComboboxRow,
  Portal,
  useComboboxContext,
  useComboboxStore,
} from "@ariakit/react";
import { filterWords } from "@platejs/combobox";
import {
  type UseComboboxInputResult,
  useComboboxInput,
  useHTMLInputCursorState,
} from "@platejs/combobox/react";
import { cva } from "class-variance-authority";
import { useComposedRef, useEditorRef } from "platejs/react";

import { cn } from "@/lib/utils";

type FilterFn = (
  item: { value: string; group?: string; keywords?: string[]; label?: string },
  search: string,
) =&gt; boolean;

interface InlineComboboxContextValue {
  filter: FilterFn | false;
  inputProps: UseComboboxInputResult["props"];
  inputRef: React.RefObject&lt;HTMLInputElement | null&gt;;
  removeInput: UseComboboxInputResult["removeInput"];
  showTrigger: boolean;
  trigger: string;
  setHasEmpty: (hasEmpty: boolean) =&gt; void;
}

const InlineComboboxContext = React.createContext&lt;InlineComboboxContextValue&gt;(
  null as unknown as InlineComboboxContextValue,
);

const defaultFilter: FilterFn = (
  { group, keywords = [], label, value },
  search,
) =&gt; {
  const uniqueTerms = new Set(
    [value, ...keywords, group, label].filter(Boolean),
  );

  return Array.from(uniqueTerms).some((keyword) =&gt;
    filterWords(keyword!, search),
  );
};

interface InlineComboboxProps {
  children: React.ReactNode;
  element: TElement;
  trigger: string;
  filter?: FilterFn | false;
  hideWhenNoValue?: boolean;
  showTrigger?: boolean;
  value?: string;
  setValue?: (value: string) =&gt; void;
}

const InlineCombobox = ({
  children,
  element,
  filter = defaultFilter,
  hideWhenNoValue = false,
  setValue: setValueProp,
  showTrigger = true,
  trigger,
  value: valueProp,
}: InlineComboboxProps) =&gt; {
  const editor = useEditorRef();
  const inputRef = React.useRef&lt;HTMLInputElement&gt;(null);
  const cursorState = useHTMLInputCursorState(inputRef);

  const [valueState, setValueState] = React.useState("");
  const hasValueProp = valueProp !== undefined;
  const value = hasValueProp ? valueProp : valueState;

  const setValue = React.useCallback(
    (newValue: string) =&gt; {
      setValueProp?.(newValue);

      if (!hasValueProp) {
        setValueState(newValue);
      }
    },
    [setValueProp, hasValueProp],
  );

  /**
   * Track the point just before the input element so we know where to
   * insertText if the combobox closes due to a selection change.
   */
  const insertPoint = React.useRef&lt;Point | null&gt;(null);

  React.useEffect(() =&gt; {
    const path = editor.api.findPath(element);

    if (!path) return;

    const point = editor.api.before(path);

    if (!point) return;

    const pointRef = editor.api.pointRef(point);
    insertPoint.current = pointRef.current;

    return () =&gt; {
      pointRef.unref();
    };
  }, [editor, element]);

  const { props: inputProps, removeInput } = useComboboxInput({
    cancelInputOnBlur: true,
    cursorState,
    ref: inputRef,
    onCancelInput: (cause) =&gt; {
      if (cause !== "backspace") {
        editor.tf.insertText(trigger + value, {
          at: insertPoint?.current ?? undefined,
        });
      }
      if (cause === "arrowLeft" || cause === "arrowRight") {
        editor.tf.move({
          distance: 1,
          reverse: cause === "arrowLeft",
        });
      }
    },
  });

  const [hasEmpty, setHasEmpty] = React.useState(false);

  const contextValue: InlineComboboxContextValue = React.useMemo(
    () =&gt; ({
      filter,
      inputProps,
      inputRef,
      removeInput,
      setHasEmpty,
      showTrigger,
      trigger,
    }),
    [
      trigger,
      showTrigger,
      filter,
      inputRef,
      inputProps,
      removeInput,
      setHasEmpty,
    ],
  );

  const store = useComboboxStore({
    // open: ,
    setValue: (newValue) =&gt; React.startTransition(() =&gt; setValue(newValue)),
  });

  const items = store.useState("items");

  /**
   * If there is no active ID and the list of items changes, select the first
   * item.
   */
  React.useEffect(() =&gt; {
    if (!store.getState().activeId) {
      store.setActiveId(store.first());
    }
  }, [items, store]);

  return (
    <span>
      &lt;ComboboxProvider
        open={
          (items.length &gt; 0 || hasEmpty) &&
          (!hideWhenNoValue || value.length &gt; 0)
        }
        store={store}
      &gt;
        &lt;InlineComboboxContext.Provider value={contextValue}&gt;
          {children}
        &lt;/InlineComboboxContext.Provider&gt;
      &lt;/ComboboxProvider&gt;
    </span>
  );
};

const InlineComboboxInput = React.forwardRef&lt;
  HTMLInputElement,
  React.HTMLAttributes&lt;HTMLInputElement&gt;
&gt;(({ className, ...props }, propRef) =&gt; {
  const {
    inputProps,
    inputRef: contextRef,
    showTrigger,
    trigger,
  } = React.useContext(InlineComboboxContext);

  const store = useComboboxContext()!;
  const value = store.useState("value");

  const ref = useComposedRef(propRef, contextRef);

  /**
   * To create an auto-resizing input, we render a visually hidden span
   * containing the input value and position the input element on top of it.
   * This works well for all cases except when input exceeds the width of the
   * container.
   */

  return (
    &lt;&gt;
      {showTrigger && trigger}

      <span>
        <span>
          {value || "\u200B"}
        </span>

        &lt;Combobox
          ref={ref}
          className={cn(
            "absolute left-0 top-0 size-full bg-transparent outline-none",
            className,
          )}
          value={value}
          autoSelect
          {...inputProps}
          {...props}
        /&gt;
      </span>
    &lt;/&gt;
  );
});

InlineComboboxInput.displayName = "InlineComboboxInput";

const InlineComboboxContent: typeof ComboboxPopover = ({
  className,
  ...props
}) =&gt; {
  // Portal prevents CSS from leaking into popover
  return (
    &lt;Portal&gt;
      &lt;ComboboxPopover
        className={cn(
          "z-500 max-h-[288px] w-[300px] overflow-y-auto rounded-md bg-popover shadow-md",
          className,
        )}
        {...props}
      /&gt;
    &lt;/Portal&gt;
  );
};

const comboboxItemVariants = cva(
  "relative mx-1 flex h-[28px] items-center rounded-sm px-2 text-sm text-foreground outline-none select-none [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
  {
    defaultVariants: {
      interactive: true,
    },
    variants: {
      interactive: {
        false: "",
        true: "cursor-pointer transition-colors hover:bg-accent hover:text-accent-foreground data-[active-item=true]:bg-accent data-[active-item=true]:text-accent-foreground",
      },
    },
  },
);

const InlineComboboxItem = ({
  className,
  focusEditor = true,
  group,
  keywords,
  label,
  onClick,
  ...props
}: {
  focusEditor?: boolean;
  group?: string;
  keywords?: string[];
  label?: string;
} & ComboboxItemProps &
  Required&lt;Pick&lt;ComboboxItemProps, "value"&gt;&gt;) =&gt; {
  const { value } = props;

  const { filter, removeInput } = React.useContext(InlineComboboxContext);

  const store = useComboboxContext()!;

  // Optimization: Do not subscribe to value if filter is false
  // biome-ignore lint/correctness/useHookAtTopLevel: This code is at top level
  const search = filter && store.useState("value");

  const visible = React.useMemo(
    () =&gt;
      !filter || filter({ group, keywords, label, value }, search as string),
    [filter, group, keywords, label, value, search],
  );

  if (!visible) return null;

  return (
    &lt;ComboboxItem
      className={cn(comboboxItemVariants(), className)}
      onClick={(event) =&gt; {
        removeInput(focusEditor);
        onClick?.(event);
      }}
      {...props}
    /&gt;
  );
};

const InlineComboboxEmpty = ({
  children,
  className,
}: React.HTMLAttributes&lt;HTMLDivElement&gt;) =&gt; {
  const { setHasEmpty } = React.useContext(InlineComboboxContext);
  const store = useComboboxContext()!;
  const items = store.useState("items");

  React.useEffect(() =&gt; {
    setHasEmpty(true);

    return () =&gt; {
      setHasEmpty(false);
    };
  }, [setHasEmpty]);

  if (items.length &gt; 0) return null;

  return (
    <div>
      {children}
    </div>
  );
};

const InlineComboboxRow = ComboboxRow;

function InlineComboboxGroup({
  className,
  ...props
}: React.ComponentProps&lt;typeof ComboboxGroup&gt;) {
  return (
    &lt;ComboboxGroup
      {...props}
      className={cn(
        "not-last:border-b hidden py-1.5 [&:has([role=option])]:block",
        className,
      )}
    /&gt;
  );
}

function InlineComboboxGroupLabel({
  className,
  ...props
}: React.ComponentProps&lt;typeof ComboboxGroupLabel&gt;) {
  return (
    &lt;ComboboxGroupLabel
      {...props}
      className={cn(
        "mb-2 mt-1.5 px-3 text-xs font-medium text-muted-foreground",
        className,
      )}
    /&gt;
  );
}

export {
  InlineCombobox,
  InlineComboboxContent,
  InlineComboboxEmpty,
  InlineComboboxGroup,
  InlineComboboxGroupLabel,
  InlineComboboxInput,
  InlineComboboxItem,
  InlineComboboxRow,
};
